﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grpc.Core;
using MX.Core.Assets;
using MX.Core.Extensions;
using MX.Core.Log;
using MX.Core.Webp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UserCenter.Api.Core;
using UserCenter.Api.Tools;
using UserCenter.BLL;
using UserCenter.Grpc;
using UserCenter.Grpc.Sdk;
using UserCenter.Models;

namespace UserCenter.Api.Services
{
    public class ConsoleApiImpl : ConsoleApi.ConsoleApiBase
    {
        ILogger logger = Logger.GetLogger(nameof(ConsoleApiImpl));

        BaseMerchantImpl _baseMerchantImpl = new BaseMerchantImpl();

        /// <summary>
        /// 错误头
        /// </summary>
        const int ECH = 0x7;

        /// <summary>
        /// 密码注册
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<RegisterResponse> PwdRegister(PwdRegisterRequest request, ServerCallContext context)
        {
            return _baseMerchantImpl.PwdRegister(request, context);
        }

        /// <summary>
        /// 密码验证
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<AuthResponse> PwdAuth(PwdAuthRequest request, ServerCallContext context)
        {
            return _baseMerchantImpl.PwdAuth(request, context);
        }


        /// <summary>
        /// 设置扩展数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<BoolValue> SetExt(SetExtRequest request, ServerCallContext context)
        {
            return _baseMerchantImpl.SetExt(request, context);
        }



        /// <summary>
        /// 设置父级
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<BoolValue> SetParent(SetParentRequest request, ServerCallContext context)
        {
            return _baseMerchantImpl.SetParent(request, context);
        }

        /// <summary>
        /// 设置密码
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<BoolValue> SetPassword(SetPasswordRequest request, ServerCallContext context)
        {
            return _baseMerchantImpl.SetPassword(request, context);
        }


        /// <summary>
        /// 设置角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<SetRoleResponse> SetRole(SetRoleRequest request, ServerCallContext context)
        {

            var role = RoleBLL.Info(context.MerchantId(), request.Key);
            if (role != null)
            {
                string iconUrl = Utils.UploadBase64Image(context, request.IconData.ToByteArray(), false);
                if (RoleBLL.Update(role.RoleId, request.Name, iconUrl, request.Description))
                {
                    return Task.FromResult(new SetRoleResponse
                    {
                        RuleId = role.RoleId
                    });
                }
                else
                {
                    context.Throw(ECH, 0x5);
                    return null;
                }
            }
            else
            {
                string iconUrl = Utils.UploadBase64Image(context, request.IconData.ToByteArray(), true);
                if (string.IsNullOrEmpty(iconUrl))
                {
                    var roleId = RoleBLL.Create(context.MerchantId(), request.Key, request.Name, iconUrl, request.Description);
                    if (roleId < 1)
                    {
                        context.Throw(ECH, 0x5);
                        return null;
                    }
                    else
                        return Task.FromResult(new SetRoleResponse
                        {
                            RuleId = roleId
                        });
                }
                else
                {
                    return null;
                }

            }

        }

        /// <summary>
        /// 设置会员的角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<BoolValue> SetMemberRole(SetMemberRoleRequest request, ServerCallContext context)
        {
            if (!MemberBLL.CheckMember(context.MerchantId(), request.MemberId))
            {
                context.Throw(ECH, 0x8);
                return null;
            }
            List<Role> merchantRoles = RoleBLL.List(context.MerchantId());
            List<int> memberRoleIds = MemberBLL.RoleIds(request.MemberId);

            var removeRoles = request.
                RemoveKeys.
                ToList().
                AsParallel().
                Select(key => merchantRoles.Take(1).SingleOrDefault(r => r.Key.Equals(key))).
                Where(r => r != null).
                Where(r => memberRoleIds.Contains(r.RoleId)).
                Select(r => r.RoleId).
                ToList();

            var addRoles = request.
               AddKeys.
               ToList().
               AsParallel().
               Select(key => merchantRoles.Take(1).SingleOrDefault(r => r.Key.Equals(key))).
               Where(r => r != null).
               Where(r => !memberRoleIds.Contains(r.RoleId)).
               Select(r => r.RoleId).
               ToList();
            bool saved = MemberBLL.SetRoles(request.MemberId, addRoles, removeRoles);
            return Task.FromResult(new BoolValue() { Value = saved });
        }


        /// <summary>
        /// 检查Token
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<CheckTokenResponse> CheckToken(CheckTokenRequest request, ServerCallContext context)
        {
            return _baseMerchantImpl.CheckToken(request, context);
        }


        /// <summary>
        /// 获取一个会员资料
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task<GetMemberResponse> GetMember(GetMemberRequest request, ServerCallContext context)
        {
            return _baseMerchantImpl.GetMember(request, context);
        }

        public override Task<GetParentListResponse> GetParentList(GetParentListRequest request, ServerCallContext context)
        {
            var response = new GetParentListResponse();
            int layer = 0;
            var memberId = request.MemberId;
            while (true)
            {
                var parentId = MemberBLL.GetParentId(memberId);
                if (parentId > 0)
                {
                    response.Layer.Add(new Grpc.Sdk.MemberLayer()
                    {
                        Layer = layer,
                        MemberId = memberId,
                        ParentId = parentId
                    });
                    memberId = parentId;
                    layer++;
                }
                else
                {
                    break;
                }
            }
            return Task.FromResult(response);
        }

        public override Task<GetChildResponse> GetChild(GetChildRequest request, ServerCallContext context)
        {
            var response = new GetChildResponse();
            var children = MemberBLL.GetChild(request.MemberId);
            response.Children.AddRange(children);
            return Task.FromResult(response);
        }

        public override Task<GetChildCountResponse> GetChildCount(GetChildCountRequest request, ServerCallContext context)
        {
            var layerCount = MemberBLL.LayerCountList(request.MemberIdList.ToList());
            var response = new GetChildCountResponse();
            response.CountList.AddRange(layerCount.Select(c => new ChildCountInfo()
            {
                ChildCount = c.ChildCount,
                GroupCount = c.GroupCount,
                MemberId = c.MemberId
            }));
            return Task.FromResult(response);
        }

        public override Task<GetMemberResponse> GetMemberByUserName(GetMemberByUserNameRequest request, ServerCallContext context)
        {
            var member = MemberBLL.Info(context.MerchantId(), request.UserName);
            if (member==null)
            {
                context.Throw(ECH, 0x8);
                return null;
            }
            return _baseMerchantImpl.GetMember(member, context);
        }



    }
}
